﻿namespace ufida.u9.ait.openapi
{
	using System;
	using System.Collections.Generic;
	using ufida.u9.ait.openapi.utils;
	using UFIDA.U9.CBO.Pub.Controller;
	using UFIDA.U9.SM.ForecastOrder;
	using UFSoft.UBF.AopFrame;
	using UFSoft.UBF.Business;

	/// <summary>
	/// ForecastOrderSaveSV partial 
	/// </summary>	
	public partial class ForecastOrderSaveSV 
	{	
		internal BaseStrategy Select()
		{
			return new ForecastOrderSaveSVImpementStrategy();	
		}		
	}
	
	#region  implement strategy	
	/// <summary>
	/// Impement Implement
	/// 
	/// </summary>	
	internal partial class ForecastOrderSaveSVImpementStrategy : BaseStrategy
	{
		public ForecastOrderSaveSVImpementStrategy() { }

		public override object Do(object obj)
		{						
			ForecastOrderSaveSV bpObj = (ForecastOrderSaveSV)obj;

			try
			{
				if (bpObj.Data == null || bpObj.Data.Count == 0)
					throw new Exception("传入参数为空");
				List<CommonArchiveDataDTOData> retlist = new List<CommonArchiveDataDTOData>();

				foreach (var dto in bpObj.Data)
				{
					ForecastOrder entity = ForecastOrder.Finder.Find($"DocNo='{dto.DocNo}'");
					if (entity == null)
					{
						//新增逻辑
						ForecastOrder doc = ForecastOrderBase.CreateDoc(dto);
						//修改单号
						using (ISession session = Session.Open())
						{
							doc.DocNo = dto.DocNo;
							session.Commit();
						}
						//审核
						doc = ForecastOrderBase.ApproveDoc(doc);
						//返回值
						CommonArchiveDataDTOData ret = new CommonArchiveDataDTOData()
						{
							ID = doc.ID,
							Code = doc.DocNo,
						};
						retlist.Add(ret);
					}
					else
					{
						//修改逻辑
						throw new AITException(599, $"单号:{dto.DocNo}已经存在,不能生成!");
					}
				}
				return ResultUtils.success(bpObj, bpObj.Data, retlist);
			}
			catch (Exception ex)
			{
				return ResultUtils.error(bpObj, bpObj.Data, ex);
			}
		}
        
    }

	#endregion
	
	
}